package com.deep.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.deep.auth.annotation.ApiController;
import com.deep.auth.feign.MemberFeignService;
import com.deep.auth.feign.ThirdPartyFeignService;
import com.deep.auth.model.vo.UserLoginVO;
import com.deep.auth.model.vo.UserRegisterVO;
import com.deep.common.model.constant.AuthConstant;
import com.deep.common.model.dto.MemberResponseVO;
import com.deep.common.model.enume.BizCodeEnum;
import com.deep.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Deep
 * @date 2022/2/4
 */
@Slf4j
@ApiController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送验证码
     *
     * @param phone 手机号
     */
    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        // 1.从redis取出验证码
        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
        //  验证码接口防刷（防止被过多使用）
        if (StringUtils.hasLength(redisCode)) {
            // 活动存入redis的时间，用当前时间减去存入redis的时间，判断用户手机号是否在60s内发送验证码
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - currentTime < 60000) {
                //60s内不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        //2.生成验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        String storageCode = code + "_" + System.currentTimeMillis();
        String storagePhone = AuthConstant.SMS_CODE_CACHE_PREFIX + phone;

        R r;
        try {
            r = thirdPartyFeignService.sendCode(storagePhone, storageCode);
            if (r.getCode() == 0) {
                log.info("验证码发送成功,手机号{},验证码{}", phone, code);
            }
        } catch (Exception e) {
            log.error("远程服务调用错误!");
            return R.error("服务不可达,请稍后再试!");
        }
        return R.ok().put("data", r);
    }

    /**
     * 用户注册
     * <p>
     * TODO: 重定向携带数据【request域失效】：利用session原理，将数据放在session中。
     * TODO: 只要跳转到下一个页面取出这个数据以后，session里面的数据就会删掉
     * TODO: 分布式下session问题
     * RedirectAttributes：重定向携带数据（传统的是model），不会丢失
     */
    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVO vos, BindingResult result, RedirectAttributes attributes) {
        // 校验vo
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors()
                    .stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors", errors);
            // 效验出错回到注册页面
            return "redirect:http://auth.mall.com/api/auth/reg.html";
            // 1、return "reg"; 请求转发【使用Model共享数据】【异常：，405 POST not support】
            // 2、"redirect:http:/reg.html"重定向【使用RedirectAttributes共享数据】【bug：会以ip+port来重定向】
            // 3、redirect:http://auth.gulimall.com/reg.html重定向【使用RedirectAttributes共享数据】
        }

        // 效验验证码
        String code = vos.getCode();

        // 获取存入Redis里的验证码
        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
        if (StringUtils.hasLength(redisCode)) {
            // 判断验证码是否正确【有BUG，如果字符串存储有问题，没有解析出code，数据为空，导致验证码永远错误】
            if (code.equals(redisCode.split("_")[0])) {
                // 删除验证码（不可重复使用）令牌机制
                redisTemplate.delete(AuthConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone());
                // 验证码通过，真正注册，调用远程服务进行注册【会员服务】
                R register = memberFeignService.register(vos);
                if (register.getCode() == 0) {
                    // 成功
                    return "redirect:http://auth.mall.com/api/auth/login.html";
                } else {
                    // 失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData("msg", new TypeReference<String>() {
                    }));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.mall.com/api/auth/reg.html";
                }
            } else {
                // 验证码错误
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.mall.com/api/auth/reg.html";
            }
        } else {
            // redis中验证码过期
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码过期");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/api/auth/reg.html";
        }
    }

    /**
     * 用户登录
     */
    @PostMapping(value = "/")
    public String login(@Valid UserLoginVO vo, RedirectAttributes attributes, HttpSession session) {
        // 远程登录
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            MemberResponseVO data = login.getData("data", new TypeReference<MemberResponseVO>() {
            });
            session.setAttribute(AuthConstant.LOGIN_USER, data);
            return "redirect:http://mall.com/api/product/index.html";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>() {
            }));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.mall.com/api/auth/login.html";
        }
    }

}
